package xyz.cerberu.cet.global.utils;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Name β世界
 * Created on 8:34
 * @Description
 */
public class JSR303Utils {

    /**
     * @author β世界 on 8:36 2020/6/15
     * 处理错误字段的报错信息
     * @param bindingResult: 错误信息
     * @return java.util.Map<java.lang.String, java.lang.Object>
     **/
    public static Map<String,Object> FieldErrors(BindingResult bindingResult){
        Map<String,Object> filedError = new HashMap<>();
        List<FieldError> errors = bindingResult.getFieldErrors();
        for (int i = 0; i < errors.size(); i++) {
            FieldError error = errors.get(i);
            filedError.put(error.getField(),error.getDefaultMessage());
        }
        return filedError;
    }

    /**
     * @author β世界 on 12:41 2020/6/20
     * 处理错误字段的报错信息，不添加不需要的字段
     * @param bindingResult:
     * @param discard:
     * @return java.util.Map<java.lang.String, java.lang.Object>
     **/
    public static Map<String,Object> FieldErrors(BindingResult bindingResult,String... discard){
        Map<String,Object> filedError = new HashMap<>();
        List<FieldError> errors = bindingResult.getFieldErrors();
        for (int i = 0; i < errors.size(); i++) {
            FieldError error = errors.get(i);
            if(ArrayUtils.contains(discard,error.getField())){ continue; }
            filedError.put(error.getField(),error.getDefaultMessage());
        }
        return filedError;
    }

    /**
     * @author β世界 on 13:25 2020/6/21
     * 获取所有的报错信息
     * @param bindingResult:
     * @return java.lang.String
     **/
    public static String FieldMessage(BindingResult bindingResult){
        StringBuffer errorInfo = new StringBuffer();
        List<FieldError> errors = bindingResult.getFieldErrors();
        for (int i = 0; i < errors.size(); i++) {
            FieldError error = errors.get(i);
            errorInfo.append(error.getDefaultMessage()+"\r\n");
        }
        return errorInfo.toString();
    }

    public static String FieldMessage(BindingResult bindingResult,String... discard){
        StringBuffer errorInfo = new StringBuffer();
        List<FieldError> errors = bindingResult.getFieldErrors();
        for (int i = 0; i < errors.size(); i++) {
            FieldError error = errors.get(i);
            if(ArrayUtils.contains(discard,error.getField())){ continue; }
            errorInfo.append(error.getDefaultMessage()+"\r\n");
        }
        return errorInfo.toString();
    }

}
